package com.tml.datastructure;

public class ListNode {

	Node head = null;
	
	/**
     * 链表添加结点:
     * 找到链表的末尾结点，把新添加的数据作为末尾结点的后续结点
     * @param data
     */
	public void addNode(int data) {
		Node newNode = new Node(data);
		if (head == null) {
			head = newNode;
			return;
		}
		Node temp = head;
		while (temp.next != null) {
			temp = temp.next;
		}
		temp.next = newNode;
	}
	
	/**
     * 链表删除结点:
     * 把要删除结点的前结点指向要删除结点的后结点，即直接跳过待删除结点
     * @param index
     * @return
     */
	public boolean deleteNode(int index) {
		if (index < 1 || index > length()) {
			return false;
		}
		if (index == 1) {
			head = head.next;
			return true;
		}
		Node prevNode = head;
		Node curNode = prevNode.next;
		int i = 1;
		while (curNode != null) {
			if (i == index) {
				prevNode.next = curNode.next;
				return true;
			}
			prevNode = prevNode.next;
			curNode = curNode.next;
			i++;
		}
		return true;
	}
	/**
	 * 计算链表长度
	 * @return
	 */
	public int length() {
		int length = 0;
		Node curNode = head;
		while (curNode.next != null) {
			length ++;
			curNode = curNode.next;
		}
		return length;
	}
	public Node linkSort() {
		Node curNode = head;
		while (curNode != null) {
			Node nextNode = curNode.next;
			while (nextNode != null) {
				if (curNode.data > nextNode.data) {
					int temp = curNode.data;
					curNode.data = nextNode.data;
					nextNode.data = temp;
				}
				nextNode = nextNode.next;
			}
			curNode = curNode.next;
		}
		return head;
	}
	/**
	 * 打印链表
	 */
	public void printLink() {
		Node curNode = head;
		while (curNode != null) {
			System.out.println(curNode.data+" \n");
			curNode = curNode.next;
		}
	}
	public void reserveLink() {
		Node curNode = head;//头结点
        Node preNode = null;//前一个结点
        while(curNode != null){
            Node nextNode = curNode.next;//保留下一个结点
            curNode.next = preNode;//指针反转
            preNode = curNode;//前结点后移
            curNode = nextNode;//当前结点后移
        }
        head = preNode;
	}
	public static void main(String[] args) {
		ListNode listNode = new ListNode();
		listNode.addNode(16);
		listNode.addNode(7);
		listNode.addNode(8);
		
		listNode.printLink();
		listNode.linkSort();
		listNode.printLink();
		listNode.reserveLink();
		listNode.printLink();
	}
}
